<template>
	<view>
		<view class="head">
			<view class="head_left" @tap="back()" v-if="isShow===false">
				<image src="../../../static/wode/return.png" mode=""></image>
				<text>返回</text>
			</view>
			<view class="head_left" v-else @tap="noDelete">
				取消
			</view>
			<view class="head_mid">
				我的相册
			</view>
			<!-- <image class="head_right" src="../../../static/wode/cream.png" mode="" @tap="gettoken('img')"></image> -->
			<view class="head_right" >
				
			</view>
		</view>
		<view class="body" v-if="isShow===false">
			<view class="box-size">
				<image class="background-img" @tap="gettoken('img')" src="/static/diqiuquan/fabu2.png" mode=""></image>
			</view>
			<view class="box-size" @longpress="addActive" :key='index' v-for="(item,index) in photoArr">
				<image @tap="previewImg(index)" class="background-img" :src="item.pic" mode=""></image>
			</view>
		</view>
		<view class="body" v-else>
			<view class="box-size" :key='index1' v-for="(item1,index1) in photoArr" @tap="selectDel(index1)">
				<image class="background-img" :src="item1.pic" mode=""></image>
				<image v-if="item1.select==false" class="uncheck-img" src="../../../static/wode/unchecked.png"></image>
				<image class="uncheck-img" v-else src="../../../static/index/theselected.png"></image>
			</view>
		</view>
		<view class='delete-box' v-if="isShow" @tap="toDelete">
			<image src="../../../static/wode/reMove.png"></image>
		</view>
	</view>
</template>

<script>
	import qiniu from "../../../common/qiniuUploader.js"

	export default {
		data() {
			return {
				isShow: false,
				picList: [],
				photo: '',
				photoList: [],
				photoArr: [],
			};
		},
		onShow() {
			if(uni.getStorageSync('user_info') != ''){
				this.getPicList()
			}
		},
		methods: {
			back() {
				uni.navigateBack({
					delta: 1
				})
			},
			noDelete() {
				this.isShow = false;
			},
			addActive() { //长按显示
				this.isShow = true;
			},
			cheacked(index) {
				for (var i = 0; i < this.picList.length; i++) {
					if (this.picList[index].isDisplay = false) {
						this.picList[index].isDisplay = true
					} else {
						this.picList[index].isDisplay = false
					}
				}
			},
			getPicList() {
				this.photoList = [];
				this.photoArr = [];
				var me = this;
				var data = {
					user_id: uni.getStorageSync('user_id')
				}
				this.myAjaxNew({
					model: 'user',
					controllerName: 'userAlbum',
					actionName: 'query',
					data: data,
					successBack: function(res) {
						me.picList = res.data.data[0]
						if (res.data.data[0].photo != null && res.data.data[0].photo != '') {
							me.photoList = res.data.data[0].photo.split(',')
							for (var j = 0; j < me.photoList.length; j++) {
								var obj = {};
								obj.pic = me.photoList[j];
								obj.select = false;
								me.photoArr.push(obj)
							}
							console.log(res.data.data)

							console.log(me.picList, '查询的图片')
							console.log(me.photoArr, '查询的图片数组')
						}
					}
				})
			},
			selectDel(index) {
				var obj = this.photoArr[index]
				if (obj.select == false) {
					obj.select = true
				} else {
					obj.select = false
				}
				// console.log(obj.select)
				this.photoArr.splice(index, 1, obj)
				console.log(this.photoArr, '选中的图片')
			},
			toDelete() {
				var me = this;
				uni.showModal({
					content: '确定删除选中图片吗',
					success: function(res) {
						if (res.confirm) {
							// console.log('用户点击确定');
							// let newPhoto = []
							me.photoList = [];
							// console.log(me.photoArr,'数组对象')
							for (var i = 0; i < me.photoArr.length; i++) {
								if (me.photoArr[i].select == false) {
									me.photoList.push(me.photoArr[i].pic)
									// console.log(newPhoto,'删除后的数组')
								} else if (me.photoArr[i].select == true) {
									me.photoArr.splice(i, 1)
								}
							}
							console.log(me.photoList, '删除后的数组')
							me.photoList = me.photoList.join(',')
							me.setPicList(me.photoList)
							me.isShow = false
						} else if (res.cancel) {
							// console.log('用户点击取消');
							me.isShow = false
						}
					}
				})
			},
			// 			qupload() {
			// 				// 选择图片
			// 				uni.chooseImage({
			// 					count: 9,
			// 					success: (res) => {
			// 						this.filePath = this.filePath.concat(res.tempFilePaths);
			// 						for (var i = 0; i < 9; i++) {
			// 							// this.key[i] = md5(Math.random().toString(36).substr(2));一开始是在这里生成后端生成token所需的key，由于没有考虑到回调函数的异步导致了key和token不匹配造成的上传失败，最后通过将key放到后端生成，前端请求后端接口时一起获取解决了这个问题
			// 							// uni.request({
			// 							// 	url: 'http://api.nauzone.cn/?service=', //后端生成key和token的接口
			// 							// 	success: (re) => {
			// 							// 		console.log(re.data.data);
			// 							// 		// this.token.push(re.data.data);
			// 							// 		//将token和key放入数组中备用，这里还有一个问题就是回调函数的this指向问题，经过经验事实发现，如果回调函数的格式写成匿名函数 success:function(){ }的样式将会导致this指向变为函数内部，这是将报this没有token和key的属性，虽然这已经在全局声明了。写成success: (re) => { } 则没有任何问题，此时回调函数内部就是全局。还有一个坑也是回调函数的异步导致的在同一个执行期上下文内，在回调函数的内部push的值在外部不能立即获取，这里需要注意一下。
			// 							// 		this.token.push(re.data.data.token);
			// 							// 		this.key.push(re.data.data.key);
			// 							// 	}
			// 							// });
			// 							if (this.photoArr.length < 9) {
			// 								var me = this;
			// 								var data = {
			// 									key: null,
			// 								}
			// 								this.myAjaxNewPost({
			// 									model: 'push',
			// 									controllerName: 'upload',
			// 									actionName: 'getToken',
			// 									data: data,
			// 									successBack: function(res) {
			// 										// me.token = res.data.data
			// 										console.log(me.token)
			// 										me.token.push(res.data.data);
			// 										me.selectImg()
			// 									}
			// 								})
			// 							} else {
			// 								uni.showToast({
			// 									title: '最多上传9张图片',
			// 									icon: 'none'
			// 								})
			// 								return
			// 							}
			// 						}
			// 					}
			// 				});
			// 			},
			// 			test() { //循环上传图片
			// 				for (var i = 0; i < 4; i++) {
			// 					//console.log(this.filePath[i]);
			// 
			// 					// console.log(this.key[i]);
			// 					console.log(this.token[i]);
			// 					qiniuUploader.upload(this.filePath[i], (res) => {
			// 						console.log(res.imageURL);
			// 					}, (error) => {
			// 						var a = JSON.stringify(error);
			// 						console.log('error: ' + a);
			// 					}, {
			// 						region: 'ECN',
			// 						domain: 'pn7r16wx7.bkt.clouddn.com', // // bucket 域名，下载资源时用到。如果设置，会在 success callback 的 res 参数加上可以直接使用的 ImageURL 字段。否则需要自己拼接
			// 						key: null, // [非必须]自定义文件 key。如果不设置，默认为使用微信小程序 API 的临时文件名
			// 						// 以下方法三选一即可，优先级为：uptoken > uptokenURL > uptokenFunc
			// 						uptoken: this.token[i],
			// 					});
			// 				}
			// 			}
			// 		},
			// #ifdef APP-PLUS
			gettoken(type) {
				this.appselectImg(type)

			},
			// #endif
			// #ifdef MP-WEIXIN
			gettoken(type) {
				var me = this;
				var data = {
					key: null,
				}
				this.myAjaxNewPost({
					model: 'push',
					controllerName: 'upload',
					actionName: 'getToken',
					data: data,
					successBack: function(res) {
						me.token = res.data.data
						console.log(me.token)
						if (me.token != '') {
							me.selectImg(type)
						}
					}
				})
			},
			// #endif
			appselectImg() {
				var me = this;
				uni.showActionSheet({
					itemList: ['拍照', '相册'],
					itemColor: '#008AFF',
					success: function(res) {
						var index = res.tapIndex;
						if (index == 1) {
							uni.chooseImage({
								count: 1,
								sizeType: ['compressed'],
								sourceType: ['album'],
								success: function(res) {
									// me.card_front = res.tempFilePaths[0];
									var filePath = res.tempFilePaths[0];
									uni.uploadFile({
										url: 'http://www.curiousmore.com:8768/eg-api/push/upload/uploadPicture',
										// url: 'http://192.168.101.14:8768/eg-api/push/upload/uploadPicture',
										filePath: filePath,
										name: 'file',
										formData: {
											'user_id': uni.getStorageSync('user_id'),
											'type': 'pic'
										},
										success: function(uploadFileRes) {
											// me.backImgArr.push(JSON.parse(uploadFileRes.data)[0]);
											console.log(JSON.parse(uploadFileRes.data)[0]);
											var imageURL = JSON.parse(uploadFileRes.data)[0];
											me.photo = imageURL
											var obj = {}
											obj.pic = me.photo;
											obj.select = false;

											me.photoArr.push(obj)
											me.photoList = me.photoList.concat(me.photo) //

											me.photoList = me.photoList.join(',')
											console.log(me.photoList, '添加后图片')
											console.log(me.photo, '添加的图片')
											me.setPicList(me.photoList)

										},
										fail: function(e) {
											uni.showToast({
												title: '图片上传失败，请重试',
												icon: 'none'
											})
											return;
										}
									});
								}
							});
						} else if (index == 0) {
							uni.chooseImage({
								count: 1,
								sizeType: ['compressed'],
								sourceType: ['camera'],
								success: function(res) {
									// me.card_front = res.tempFilePaths[0];

									var filePath = res.tempFilePaths[0];
									uni.uploadFile({
										url: 'http://www.curiousmore.com:8768/eg-api/push/upload/uploadPicture',
										// url: 'http://192.168.101.14:8768/eg-api/push/upload/uploadPicture',
										filePath: filePath,
										name: 'file',
										formData: {
											'user_id': uni.getStorageSync('user_id'),
											'type': 'pic'
										},
										success: function(uploadFileRes) {
											// me.backImgArr.push(JSON.parse(uploadFileRes.data)[0]);
											console.log(JSON.parse(uploadFileRes.data)[0]);
											var imageURL = JSON.parse(uploadFileRes.data)[0];
											me.photo = imageURL
											var obj = {}
											obj.pic = me.photo;
											obj.select = false;

											me.photoArr.push(obj)
											me.photoList = me.photoList.concat(me.photo) //

											me.photoList = me.photoList.join(',')
											console.log(me.photoList, '添加后图片')
											console.log(me.photo, '添加的图片')
											me.setPicList(me.photoList)

										},
										fail: function(e) {
											uni.showToast({
												title: '图片上传失败，请重试',
												icon: 'none'
											})
											return;
										}
									});
								}
							});
						}
					}
				});
			},
			selectImg() { //上传图片
				var me = this;
				uni.showActionSheet({
					itemList: ['拍照', '相册'],
					itemColor: '#008AFF',
					success: function(res) {
						var index = res.tapIndex;
						if (index == 1) {
							uni.chooseImage({
								count: 1,
								sizeType: ['compressed'],
								sourceType: ['album'],
								success: function(res) {
									// me.card_front = res.tempFilePaths[0];
									var filePath = res.tempFilePaths[0];
									// 交给七牛上传
									uni.showLoading({
										title: '上传中'
									})
									if (me.token != '') {
										qiniu.upload(filePath, (res) => {
											console.log(res.imageURL)
											var imageURL = res.imageURL
											me.photo = imageURL
											var obj = {}
											obj.pic = me.photo;
											obj.select = false;

											me.photoArr.push(obj)
											me.photoList = me.photoList.concat(me.photo) //

											me.photoList = me.photoList.join(',')
											console.log(me.photoList, '添加后图片')
											console.log(me.photo, '添加的图片')
											me.setPicList(me.photoList)
											uni.hideLoading()
											console.log(me.picList)
											console.log('file url is: ' + res.fileUrl);
										}, (error) => {
											console.log('error: ' + error);
										}, {
											region: 'ECN',
											domain: 'http://img.curiousmore.com', // // bucket 域名，下载资源时用到。如果设置，会在 success callback 的 res 参数加上可以直接使用的 ImageURL 字段。否则需要自己拼接
											key: null, // [非必须]自定义文件 key。如果不设置，默认为使用微信小程序 API 的临时文件名
											// 以下方法三选一即可，优先级为：uptoken > uptokenURL > uptokenFunc
											uptoken: me.token, // 由其他程序生成七牛 uptoken
											// uptokenURL: 'http://192.168.6.6:8768/eg-api/push/upload/getToken', // 从指定 url 通过 HTTP GET 获取 uptoken，返回的格式必须是 json 且包含 uptoken 字段，例如： {"uptoken": "[yourTokenString]"}
											uptokenFunc: function() {
												return '[yourTokenString]';
											}
										}, (res) => {
											console.log('上传进度', res.progress)
											console.log('已经上传的数据长度', res.totalBytesSent)
											console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)

										}, () => {
											// 取消上传
										}, () => {
											// `before` 上传前执行的操作
										}, (err) => {

											// `complete` 上传接受后执行的操作(无论成功还是失败都执行)
										});
									}
								}
							});
						} else if (index == 0) {
							uni.chooseImage({
								count: 1,
								sizeType: ['compressed'],
								sourceType: ['camera'],
								success: function(res) {
									// me.card_front = res.tempFilePaths[0];
									console.log(res);
									var filePath = res.tempFilePaths[0];
									// 交给七牛上传

									if (me.token != '') {
										uni.showLoading({
											title: '上传中'
										})
										qiniu.upload(filePath, (res) => {
											console.log(res.imageURL)
											var imageURL = res.imageURL
											me.photo = imageURL
											var obj = {}
											obj.pic = me.photo;
											obj.select = false;

											me.photoArr.push(obj)
											me.photoList = me.photoList.concat(me.photo) //

											me.photoList = me.photoList.join(',')
											console.log(me.photoList, '添加后图片')
											console.log(me.photo, '添加的图片')
											me.setPicList(me.photoList)
											uni.hideLoading()
											console.log('file url is: ' + res.fileUrl);
										}, (error) => {
											console.log('error: ' + error);
										}, {
											region: 'ECN',
											domain: 'http://img.curiousmore.com', // // bucket 域名，下载资源时用到。如果设置，会在 success callback 的 res 参数加上可以直接使用的 ImageURL 字段。否则需要自己拼接
											key: null, // [非必须]自定义文件 key。如果不设置，默认为使用微信小程序 API 的临时文件名
											// 以下方法三选一即可，优先级为：uptoken > uptokenURL > uptokenFunc
											uptoken: me.token, // 由其他程序生成七牛 uptoken
											// uptokenURL: 'http://192.168.6.6:8768/eg-api/push/upload/getToken', // 从指定 url 通过 HTTP GET 获取 uptoken，返回的格式必须是 json 且包含 uptoken 字段，例如： {"uptoken": "[yourTokenString]"}
											uptokenFunc: function() {
												return '[yourTokenString]';
											}
										}, (res) => {
											console.log('上传进度', res.progress)
											console.log('已经上传的数据长度', res.totalBytesSent)
											console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)

										}, () => {
											// 取消上传
										}, () => {
											// `before` 上传前执行的操作
										}, (err) => {


											// `complete` 上传接受后执行的操作(无论成功还是失败都执行)
										});


									}
								}
							});
						}
					}
				});
			},
			setPicList(photoList) {
				var me = this;
				var data = {
					user_id: uni.getStorageSync('user_id'),
					photo: photoList
				}
				this.myAjaxNewPost({
					model: 'user',
					controllerName: 'userAlbum',
					actionName: 'insert',
					data: data,
					successBack: function(res) {
						console.log(res)
						if (res.data.code == 0) {
							uni.showToast({
								title: '删除成功',
								icon: 'none'
							})
							console.log(me.photoList)
						}
					}
				})
			},
			previewImg(index) { // 预览图片
				var me = this;
				console.log(this.photoList, '显示照片')
				uni.previewImage({
					current: me.photoList[index], //显示当前点击图册
					urls: me.photoList,
				})
			},
		},
	}
</script>

<style scoped>
	.head {
		width: 100%;
		height: 162upx;
		position: fixed;
		top: 0;
		display: flex;
		justify-content: space-between;
		font-size: 32upx;
		padding: 0 24upx;
		background: #ffffff;
		box-sizing: border-box;
		z-index: 9999;
	}

	.head_left image {
		height: 36upx;
		width: 20upx;
		margin-right: 9upx;
	}

	.head_left {
		display: flex;
		align-items: center;
		color: #666666;
		padding-top: 70upx;
	}

	.head_mid {
		font-size: 36upx;
		color: #333333;
		padding-top: 90upx;
	}

	.head_right {
		width: 92upx;
	}

	.body {
		display: flex;
		flex-wrap: wrap;
		padding: 24upx 0 0 30upx;
		position: relative;
		top: 162upx;
	}

	.box-size {
		width: 215upx;
		height: 215upx;
		margin: 0 24upx 24upx 0;
		position: relative;
		display: flex;
		flex-wrap: wrap;
	}

	.background-img {
		width: 100%;
		height: 100%;
		border-radius: 20upx;
		overflow: hidden;
	}

	.uncheck-img {
		width: 48upx;
		height: 48upx;
		position: absolute;
		top: 10upx;
		right: 10upx;
	}

	.border-radius {
		width: 46upx;
		height: 46upx;
		border: 2upx solid white;
		background: rgba(0, 0, 0, .4);

	}

	.delete-box {
		width: 100%;
		height: 88upx;
		background: rgba(0, 0, 0, 1);
		opacity: 0.5;
		position: fixed;
		display: flex;
		justify-content: center;
		align-items: center;
		bottom: 0;
	}

	.delete-box image {
		width: 52upx;
		height: 58upx;
	}
</style>
